package com.dotstone.chipism.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.adapter.WlanSelectAdapter;
import com.dotstone.chipism.bean.Device;
import com.dotstone.chipism.bean.DeviceType;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.bean.Key;
import com.dotstone.chipism.ui.login.LoginActivity;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.NetUtil;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.util.Util;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class WlanSelectionActivity extends BaseActivity {
	private LinearLayout mBackL;
	private TextView mTitleT;
	private ListView mWlanLv;
	private TextView tv_statusBar_mian;
	private List<Device> mDevices = new ArrayList<Device>();
	private WlanSelectAdapter mWlanAdapter;
	private int entry;

	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_layout:
			finish();
			break;

		default:
			break;
		}
	}
	
	Handler mHandler = new Handler() {
		public void handleMessage(final Message msg) {
			switch (msg.what) {
			case 1:
				initData();
				SocketManager.getInstance().initSocket(WlanSelectionActivity.this);
				break;
		
			default:
				break;
			}
		}
	};

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_wlan_selection;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		mBackL = $(R.id.back_layout);
		mTitleT = $(R.id.title_tv);
		mTitleT.setVisibility(View.GONE);
		tv_statusBar_mian = $(R.id.tv_statusBar_mian);
		mWlanLv = $(R.id.wlan_lv);
		entry = getIntent().getIntExtra("entry", 0);
		boolVersion();
		initData();
		getAllDevice();
		mBackL.setOnClickListener(this);
		mWlanLv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
				// TODO Auto-generated method stub
				if(mDevices.get(position).getRole()!=1){
					ToastShow.Show(getApplicationContext(), "分享的网关不能搜索设备");
					return;
				}
				Intent intent = new Intent();

				intent = new Intent(WlanSelectionActivity.this, AddDeviceTypeSelectionActivity.class);
				Log.i("wmy", "所选的网关地址为" + mDevices.get(position).getDeviceAddress());
				Log.i("wmy", "所选的网关名称为" + mDevices.get(position).getDeviceName());
				DeviceManager.getInstance().setmWlanBssid(mDevices.get(position).getDeviceAddress());
				Log.i("wmy", "所选的网关ID为" + mDevices.get(position).getDeviceID());
				DeviceManager.getInstance().setmWlanId(mDevices.get(position).getDeviceID());
				startActivity(intent);
				finish();
			}
		});
	}
	
	private void getAllDevice(){
		if (NetUtil.isNetworkAvailable(getApplicationContext())) {
			if (!Util.isLogin(getApplicationContext())) {
				return;
			}
			RequestParams params = new RequestParams(HttpURL.GET_DEVICE_URL);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			try {
				obj.put("key", "10000");
				obj.put("hid", DeviceManager.getInstance().hid);
				obj.put("requestTime", "" + System.currentTimeMillis());
				obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
				// Log.e("test", " get all obj = " + obj.toString());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					// Log.e("wmy", "get all activity =" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);
						String resultCode = jsonObject.getString("resultCode");
						if (resultCode.equals("1")) {
							DeviceManager.getInstance().clearDevice();
							JSONArray data = jsonObject.getJSONArray("data");
							// Log.e("wmy", "length " + data.length());
							if (data.length() != 0) {
								for (int i = 0; i < data.length(); i++) {
									JSONObject deviceInfo = data.getJSONObject(i).getJSONObject("deviceInfo");
									String deviceId = deviceInfo.getString("deviceId");
									String deviceWifiSSID = deviceInfo.getString("deviceWifiSSID");
									String deviceAddress = deviceInfo.optString("deviceAddress");
									int deviceType = deviceInfo.getInt("deviceType");
									String deviceModel = deviceInfo.getString("deviceModel");
									String deviceName = data.getJSONObject(i).getString("remarks");// deviceName
									int status = deviceInfo.optInt("deviceStatus");
									int role = data.getJSONObject(i).optInt("role");
									String userId = deviceInfo.getString("userId");
									String mainDeviceId = deviceInfo.optString("mainDeviceId");
									Device device = new Device();
									device.setDeviceID(deviceId);
									device.setDeviceWifiSsid(deviceWifiSSID);
									device.setDeviceType(deviceType);
									device.setDeviceBrand(deviceModel);
									device.setDeviceName(deviceName);
									device.setStatus(status);
									device.setRole(role);
									device.setUserId(userId);
									if (deviceType == DeviceType.DEVICE_TYPE_AIR_CONTROLLER
											|| deviceType == DeviceType.DEVICE_TYPE_BOX2
											|| deviceType == DeviceType.DEVICE_TYPE_DVD
											|| deviceType == DeviceType.DEVICE_TYPE_FAN
											|| deviceType == DeviceType.DEVICE_TYPE_TV
											|| deviceType == DeviceType.DEVICE_TYPE_PROJECTOR) {
										// 是遥控器
										JSONArray ja = data.getJSONObject(i).getJSONArray("deviceButton");
										List<Key> keys = new ArrayList<Key>();
										for (int n = 0; n < ja.length(); n++) {
											Key key = new Key();
											JSONObject joKey = ja.getJSONObject(n);
											key.setKeyNum(joKey.getInt("position"));
											key.setCodeValue(joKey.getString("buttonCmd"));
											keys.add(key);
										}
										device.setKeys(keys);
									}
									if (deviceType != DeviceType.DEVICE_TYPE_WLAN) {
										device.setMainDeviceId(mainDeviceId);
									}
									device.setDeviceAddress(deviceAddress);
									DeviceManager.getInstance().addDevice(device);
								}
							}
							Message msg = Message.obtain();
							msg.what = 1;
							mHandler.sendMessage(msg);

						} else if (resultCode.equals("10003")) {
							// 在这里判断token有效性
							Toast.makeText(getApplicationContext(), "您的登陆已超时，请重新登陆", Toast.LENGTH_SHORT).show();
							startActivity(new Intent(getApplicationContext(), LoginActivity.class));
							finish();
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onCancelled(CancelledException arg0) {
				}

				@Override
				public void onError(Throwable arg0, boolean arg1) {
					// lt.error();
				}

				@Override
				public void onFinished() {
				}
			});
		}
	}

	private void initData() {
		mDevices = DeviceManager.getInstance().getWlans();
		mWlanAdapter = new WlanSelectAdapter(getApplicationContext(), mDevices);
		mWlanLv.setAdapter(mWlanAdapter);
	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(
			// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) tv_statusBar_mian
					.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			tv_statusBar_mian.setLayoutParams(layoutParams1);
			tv_statusBar_mian.setVisibility(View.VISIBLE);
		} else {
			tv_statusBar_mian.setVisibility(View.GONE);
		}
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

}
